#include "../include/head.h"
// 创建服务端

int listenFd;
int clientFd[NUM] = {0};
pthread_t pts[NUM];
void *f(void *a)
{
    long i = (long)a;
    // 6 通信
    int r;
    char reqString[1024];
    while (1)
    {
        memset(reqString, 0, sizeof(reqString));
        r = recv(clientFd[i], reqString, sizeof(Req), 0);
        reqString[r] = '\0';
        // reqString是qt语言发送过来的QByteArray数据，需要处理一下
        printf("*************************\n");
        printf("reqString:%s\n", reqString);
        printf("*************************\n");
        if (r > 0)
        {
            // 判断reqString不为空
            if (strlen(reqString) > 0)
            {
                const char delim = '^';
                int arrayLength = 0;
                char **tokens = splitStringCorrect(reqString, delim, &arrayLength);
                int r = 1;
                if (strcmp(tokens[0], "1000") == 0)
                {
                    // 登录
                    char sqlData[1024];
                    int userId;
                    memset(sqlData, 0, sizeof(sqlData));
                    int r = sql_select_userInfo_by_account_password(tokens[1], tokens[2], sqlData, &userId);
                    if (r)
                    {
                        int bytesSent = send(clientFd[i], sqlData, strlen(sqlData), 0);
                        if (bytesSent == -1)
                        {
                            perror("send failed");
                        }
                        else
                        {
                            int flag = 1;
                            // 遍历该账号是否已经链接
                            for (int i = 0; i < Client_Info_length; i++)
                            {
                                if (Client_Info[i].userId == userId)
                                {
                                    // 当前用户已经连接过，但是该用户又退出了，重新登录
                                    if (Client_Info[i].isLogin == 0)
                                    {
                                        Client_Info[i].isLogin = 1;
                                    }
                                    flag = 0;
                                }
                            }
                            // 没有登录，往Client_Info插入一条数据
                            if (flag)
                            {
                                Client_Info[Client_Info_length].index = i;
                                Client_Info[Client_Info_length].fd = clientFd[i];
                                Client_Info[Client_Info_length].isLogin = 1;
                                Client_Info[Client_Info_length].userId = userId;
                                Client_Info_length++;
                            }
                        }
                    }
                    else
                    {
                        char tip[] = "account or password error";
                        char errCode = 'x';
                        // 登录失败
                        snprintf(sqlData, 1024, "%d^%c^%s", 1000, errCode, tip);
                        printf("sqlData:%s\n", sqlData);
                        printf("-------------------------\n");
                        printf("登录返回数据：length:%zu,---,%s\n", strlen(sqlData), sqlData);
                        printf("-------------------------\n");
                        int bytesSent = send(clientFd[i], sqlData, strlen(sqlData), 0);
                        if (bytesSent == -1)
                        {

                            perror("send failed");
                        }
                    }
                }
                else if (strcmp(tokens[0], "1001") == 0)
                {
                    int uid = atoi(tokens[1]); // 将 tokens[1] 转换为整数
                    // 会话列表
                    char sqlData[2048];
                    int total = 0;
                    memset(sqlData, 0, sizeof(sqlData));
                    sql_select_ConversationWindow(uid, sqlData, &total, 1001);
                    printf("-------------------------\n");
                    printf("用户列表：length:%zu,---,%s\n", strlen(sqlData), sqlData);
                    printf("-------------------------\n");
                    int bytesSent = send(clientFd[i], sqlData, strlen(sqlData), 0);
                    if (bytesSent == -1)
                    {
                        perror("send failed");
                    }
                }
                else if (strcmp(tokens[0], "1002") == 0)
                {
                    int uid = atoi(tokens[1]); // 将 tokens[1] 转换为整数
                    // 会话消息列表
                    char sqlData[2048];
                    memset(sqlData, 0, sizeof(sqlData));
                    int total = 0;
                    // 接口id、 用户id、好友id、群id、性别、消息类型(1普通，2文件)、用户名、昵称、消息、文件后缀
                    if (strcmp(tokens[3], "0") != 0)
                    {                                  // 群聊
                        int GroupId = atoi(tokens[3]); // 将 tokens[3] 转换为整数
                        sql_select_wechar_public_message(GroupId, sqlData, &total, 1002);
                    }
                    else
                    {                                   // 单聊
                        int friendId = atoi(tokens[2]); // 将 tokens[2] 转换为整数
                        sql_select_wechar_message(uid, friendId, sqlData, &total, 1002);
                    }

                    // 如果sqlData为空，则发送一个空字符串给客户端
                    if (strlen(sqlData) == 0)
                    {
                        strcpy(sqlData, "1002^0");
                    }
                    printf("-------------------------\n");
                    printf("聊天内容列表：length:%zu,---,%s\n", strlen(sqlData), sqlData);
                    printf("-------------------------\n");
                    int bytesSent = send(clientFd[i], sqlData, strlen(sqlData), 0);
                    if (bytesSent == -1)
                    {
                        perror("send failed");
                    }
                }
                else if (strcmp(tokens[0], "1003") == 0)
                {
                    printf("1003-0\n");
                    int uid = atoi(tokens[1]); // 将 tokens[1] 转换为整数
                    sql_insert_char(reqString);
                    char sqlData[2048];
                    memset(sqlData, 0, sizeof(sqlData));
                    int total = 0;
                    int bytesSent;
                    if (strcmp(tokens[3], "0") != 0)
                    {
                        printf("1003-1\n");
                        // 发送群聊消息
                        int GroupId = atoi(tokens[3]); // 将 tokens[1] 转换为整数
                        sql_select_wechar_public_message(GroupId, sqlData, &total, 1002);
                        // 如果是公共频道群聊groupId为10086，
                        for (int j = 0; j < NUM; j++)
                        {
                            if (clientFd[j])
                            {
                                printf("-------------------------\n");
                                printf("群聊聊天返回列表：length:%zu,---,%s\n", strlen(sqlData), sqlData);
                                printf("-------------------------\n");
                                bytesSent = send(clientFd[j], sqlData, strlen(sqlData), 0);
                            }
                        }
                    }
                    else
                    {
                        printf("1003-2\n");
                        int friendId = atoi(tokens[2]); // 将 tokens[2] 转换为整数
                        // 发送单聊消息
                        sql_select_wechar_message(uid, friendId, sqlData, &total, 1002);
                        // 查找好有是否在线
                        for (int f = 0; f < Client_Info_length; f++)
                        {
                            if (Client_Info[f].userId == friendId)
                            {
                                // 获取sqlData的数据的长度，并符给length
                                printf("-------------------------\n");
                                printf("单聊发送消息后给好友：length:%zu,---,%s\n", strlen(sqlData), sqlData);
                                printf("-------------------------\n");
                                int bytesSent = send(Client_Info[f].fd, sqlData, strlen(sqlData), 0);
                                if (bytesSent == -1)
                                {
                                    perror("send friend failed");
                                }
                            }
                        }
                        // 获取sqlData的数据的长度，并符给length
                        printf("-------------------------\n");
                        printf("单聊发送消息后返回：length:%zu,---,%s\n", strlen(sqlData), sqlData);
                        printf("-------------------------\n");

                        bytesSent = send(clientFd[i], sqlData, strlen(sqlData), 0);
                    }
                    if (bytesSent == -1)
                    {
                        perror("send failed");
                    }
                }
                else if (strcmp(tokens[0], "1009") == 0)
                {
                    // 接收文件
                    // char sqlData[2048] = tokens[1];
                }
                else
                {
                    printf("err connet %d,%s\n", clientFd[i], reqString);
                }
            }
        }
        else if (r == 0)
        {
            // 客户端关闭连接
            printf("Client %d disconnected\n", clientFd[i]);
            for (int j = 0; j < Client_Info_length; j++)
            {
                if (clientFd[i] == Client_Info[j].fd)
                {
                    Client_Info[j].isLogin = 0;
                    Client_Info[j].index = 99999;
                }
            }
            break;
        }
        else
        {
            // recv 出错
            perror("recv failed");
            break;
        }
    }
}

void hand(int s)
{
    if (2 == s)
    {
        printf("关闭服务器!\n");
        // 7 断开连接
        for (int i = 0; i < NUM; i++)
            if (clientFd[i])
            {
                close(clientFd[i]);
                pthread_cancel(pts[i]);
            }
        close(listenFd);
        exit(1);
    }
}
int service_init()
{
    signal(2, hand); // 用来关闭的
    // 1 创建socket
    listenFd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == listenFd)
        printf("create socket err:%m\n"), exit(-1);
    printf("create socket success%m\n");

    // 2 创建服务器协议地址簇
    struct sockaddr_in sAddr = {0};
    sAddr.sin_family = AF_INET;
    sAddr.sin_addr.s_addr = inet_addr("192.168.70.230");
    // sAddr.sin_addr.s_addr = inet_addr("192.168.124.28"); // 家里
    sAddr.sin_port = htons(9999);

    // 3 绑定
    int r = bind(listenFd, (struct sockaddr *)&sAddr, sizeof sAddr);
    if (-1 == listenFd)
        printf("bind err:%m\n"), close(listenFd), exit(-1);
    printf("bind succ %m\n");

    // 4 监听
    r = listen(listenFd, 10);
    if (-1 == listenFd)
        printf("listener err:%m\n"), close(listenFd), exit(-1);
    printf("listener succ %m\n");

    // 5 接受客户端连接
    for (long i = 0; i < NUM; i++)
    {
        clientFd[i] = accept(listenFd, NULL, NULL);
        if (-1 == clientFd[i])
            printf("service err:%m\n"), close(listenFd), exit(-1);
        printf("connet succ:%d\n", clientFd[i]); // 一般是4
        pthread_create(&pts[i], NULL, f, (void *)i);
    }

    return 0;
}